package com.mantru.iotpot.Cook.adapter;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.mantru.iotpot.DateClass.FirePowerDate;
import com.mantru.iotpot.R;

import java.util.ArrayList;
import java.util.List;

public class FirePowerAdapter extends RecyclerView.Adapter<FirePowerAdapter.FirePowerViewHolder> {
    private List<FirePowerDate> firePowerDataList;//原数据
    private Context context;
    private List<FirePowerDate> filteredList; // 只包含 is_show=1 的项

    public FirePowerAdapter(List<FirePowerDate> firePowerDataList,Context context) {
        this.firePowerDataList = firePowerDataList;
        this.context = context;
        // 创建过滤后的列表
        filteredList = new ArrayList<>();
        for (FirePowerDate item : firePowerDataList) {
            if (item.getIs_show() == 1) {
                filteredList.add(item);
            }
        }
    }
    @NonNull
    @Override
    public FirePowerAdapter.FirePowerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.adapter_frie_power, parent, false);
        return new FirePowerViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FirePowerAdapter.FirePowerViewHolder holder, int position) {
        // 使用 holder.getAdapterPosition() 获取当前最新的位置
        int currentPosition = holder.getAdapterPosition();
        if (currentPosition == RecyclerView.NO_POSITION) return;

        // 获取过滤后的当前项
        FirePowerDate filteredItem = filteredList.get(currentPosition);

        // 查找在原始列表中的位置
        int originalPosition = firePowerDataList.indexOf(filteredItem);
        if (originalPosition == -1) return;

        FirePowerDate originalItem = firePowerDataList.get(originalPosition);

        // 绑定数据到视图
        holder.box.setVisibility(View.VISIBLE);
        holder.title1.setText(filteredItem.getTitle1());
        holder.title2.setText(filteredItem.getTitle2());
        holder.minus_text.setText("-" + filteredItem.getStep_value() + filteredItem.getUnit());
        holder.add_text.setText("+" + filteredItem.getStep_value() + filteredItem.getUnit());
        holder.seekBar.setProgress(Integer.parseInt(filteredItem.getValue()));
        holder.seekBar.setMax(Integer.parseInt(filteredItem.getMax_value()));
        holder.value.setText(filteredItem.getValue());

        updateBubble(holder, currentPosition);

        // 确保父容器的宽度已经正确计算
        holder.itemView.findViewById(R.id.seekBar_box).getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        holder.itemView.findViewById(R.id.seekBar_box).getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        updateBubble(holder, currentPosition);
                    }
                });

        // SeekBar 监听器
        holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            private int roundedProgress;

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    // 计算舍入后的进度值
                    int stepValue = Integer.parseInt(originalItem.getStep_value());
                    roundedProgress = (progress / stepValue) * stepValue;
                    roundedProgress = Math.max(0, Math.min(roundedProgress, seekBar.getMax()));

                    // 更新原始数据
                    originalItem.setValue(String.valueOf(roundedProgress));
                    holder.value.setText(String.valueOf(roundedProgress));
                    updateBubble(holder, currentPosition);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (roundedProgress == 0) {
                    originalItem.setValue(String.valueOf(roundedProgress + 1));
                } else {
                    originalItem.setValue(String.valueOf(roundedProgress));
                }
                updateBubble(holder, currentPosition);
            }
        });

        // 加号按钮
        holder.add.setOnClickListener(v -> {
            int currentValue = Integer.parseInt(originalItem.getValue());
            int stepValue = Integer.parseInt(originalItem.getStep_value());
            int maxValue = Integer.parseInt(originalItem.getMax_value());

            int newValue = currentValue + stepValue;
            newValue = Math.min(newValue, maxValue);

            holder.seekBar.setProgress(newValue);
            originalItem.setValue(String.valueOf(newValue));
            updateBubble(holder, currentPosition);
        });

        // 减号按钮
        holder.minus.setOnClickListener(v -> {
            int currentValue = Integer.parseInt(originalItem.getValue());
            int stepValue = Integer.parseInt(originalItem.getStep_value());

            int newValue = currentValue - stepValue;
            newValue = Math.max(newValue, 0);

            holder.seekBar.setProgress(newValue);
            if (newValue == 0) {
                originalItem.setValue(String.valueOf(newValue + 1));
            } else {
                originalItem.setValue(String.valueOf(newValue));
            }
            updateBubble(holder, currentPosition);
        });
    }

    @Override
    public int getItemCount() {
        return filteredList.size();
    }

    public static class FirePowerViewHolder extends RecyclerView.ViewHolder{
        private final RelativeLayout box;
        TextView title1,title2,minus_text,add_text,value;
        ImageView minus,add;
        SeekBar seekBar;
        FrameLayout valueBox;
        public FirePowerViewHolder(@NonNull View itemView) {
            super(itemView);
            title1 = itemView.findViewById(R.id.frie_power_adapter_title1);
            title2 = itemView.findViewById(R.id.frie_power_adapter_title2);
            minus_text = itemView.findViewById(R.id.frie_power_adapter_minus_text);
            add_text = itemView.findViewById(R.id.frie_power_adapter_add_text);
            minus = itemView.findViewById(R.id.frie_power_adapter_minus_img);
            add = itemView.findViewById(R.id.frie_power_adapter_add_img);
            seekBar = itemView.findViewById(R.id.frie_power_adapter_seekbar);
            valueBox = itemView.findViewById(R.id.frie_power_adapter_Value_box);
            value = itemView.findViewById(R.id.frie_power_adapter_Value);
            box = itemView.findViewById(R.id.frie_power_adapter_box);
        }
    }

    public void updateBubble(FirePowerViewHolder holder, int position) {
        SeekBar seekBar = holder.seekBar;
        FrameLayout valueBox = holder.valueBox;
        TextView valueText = holder.value;
        // 更新气泡内容
        // 直接获取当前进度值而不是从数据源
        int currentProgress = holder.seekBar.getProgress();
        holder.value.setText(String.valueOf(currentProgress));
        // 获取父容器的范围
        RelativeLayout parentLayout = holder.itemView.findViewById(R.id.seekBar_box);
        parentLayout.post(new Runnable() {
            @Override
            public void run() {
                int parentWidth = parentLayout.getWidth();
                int seekBarWidth = seekBar.getWidth();
                // 计算滑块的位置（使用进度计算，避免滑块偏移问题）
                int progress = seekBar.getProgress();
                int thumbPosition = seekBar.getThumbOffset() + (int) (progress * ((float) seekBarWidth / seekBar.getMax()));
                // 考虑布局方向
                if (seekBar.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
                    thumbPosition = parentWidth - thumbPosition;
                }
                // 计算气泡的水平位置（相对于父容器）
                int bubbleX = thumbPosition - valueBox.getWidth() / 2;
                // 确保气泡不会超出父容器的左右边界
                bubbleX = Math.max(0, Math.min(bubbleX, parentWidth - valueBox.getWidth()));

                // 气泡的垂直位置（固定在 SeekBar 的上方）
                int bubbleY = -valueBox.getHeight() - 10; // 调整偏移量

                // 更新气泡位置
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) valueBox.getLayoutParams();
                layoutParams.removeRule(RelativeLayout.CENTER_HORIZONTAL);
                layoutParams.leftMargin = bubbleX;
                layoutParams.topMargin = bubbleY;

                valueBox.setLayoutParams(layoutParams);
                valueBox.requestLayout(); // 强制刷新布局

                Log.d("updateBubble", "position: " + position + "\nbubbleX: " + bubbleX + "\nbubbleY" + bubbleY);
            }
        });
    }

    public void updateSeekBarAndBubble(FirePowerViewHolder holder, int filteredPosition) {
        // 获取过滤后的当前项
        FirePowerDate filteredItem = filteredList.get(filteredPosition);

        // 查找在原始列表中的位置
        int originalPosition = firePowerDataList.indexOf(filteredItem);
        if (originalPosition == -1) return;

        // 使用原始数据更新视图
        String currentValue = firePowerDataList.get(originalPosition).getValue();
        int progress = Integer.parseInt(currentValue);
        holder.seekBar.setProgress(progress);
        updateBubble(holder, filteredPosition);
    }

    // 添加一个方法来获取修改后的 firePowerDataList 数据
    public List<FirePowerDate> getFirePowerDataList() {
        return firePowerDataList;
    }

}
